package com.mvc.web.common.utils;

import java.beans.PropertyDescriptor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtilsBean;
import org.apache.commons.lang.StringUtils;


/**   
* @Description: 内部接口调用
* @author 白海安 （bai.ha@qmaiche.com） 2015年8月27日 上午11:24:37
* @version V1.0   
*/
public class HttpUtil {
	
	
	public static String sendGet(String url, String param,String header_key,String header_value) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            connection.setRequestProperty("Cookie", "PLAY_FLASH=\"ticketId=6f70d2f1-4b95-458f-8e04-55984078da8e&skipLog=false&userId=U005E&skipAuth=false\"");
            connection.setRequestProperty("_ccsignature", "U005E@-1417819468");
            connection.setRequestProperty("_cctid", "6f70d2f1-4b95-458f-8e04-55984078da8e");
            connection.setRequestProperty("_sysMaxAge", "1800");
            connection.setRequestProperty("_tid", "6f70d2f1-4b95-458f-8e04-55984078da8e@hollycc");
            connection.setRequestProperty("_timediff", "-266");
            
            
            
           /* if(StringUtils.isNotEmpty(header_key) && StringUtils.isNotEmpty(header_value)){
            	connection.setRequestProperty(header_key, header_value);
            }*/
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
	
	 /**
	   * 向指定 URL 发送POST方法的请求
	   * 
	   * @param url
	   *            发送请求的 URL
	   * @param param
	   *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	   * @return 所代表远程资源的响应结果
	   */
      public static String sendPost(String url, String param) {
    	  PrintWriter out = null;
    	  BufferedReader in = null;
    	  String result = "";
    	  try {
    		  URL realUrl = new URL(url);
    		  // 打开和URL之间的连接
    		  URLConnection conn = realUrl.openConnection();
    		  // 设置通用的请求属性
    		  conn.setRequestProperty("accept", "*/*");
    		  conn.setRequestProperty("connection", "Keep-Alive");
    		  conn.setRequestProperty("user-agent",
    				  "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
              conn.setRequestProperty("Accept-Charset", "utf-8");
              conn.setRequestProperty("contentType", "utf-8");
              conn.setRequestProperty("Cookie", "JSESSIONID=alix_04!!D6CDFC79DE6194013BD1DB372585EED1.jvm_11");
    		  // 发送POST请求必须设置如下两行
    		  conn.setDoOutput(true);
    		  conn.setDoInput(true);
    		  conn.setReadTimeout(2000);
    		  conn.setAllowUserInteraction(true);
              conn.getOutputStream().write(param.getBytes("UTF-8"));
    		  // 定义BufferedReader输入流来读取URL的响应
    		  in = new BufferedReader(
    				  new InputStreamReader(conn.getInputStream(),"GBK"));
    		  String line;
    		  while ((line = in.readLine()) != null) {
    			  result += line;
    		  }
    	  } catch (Exception e) {
    		  System.out.println("发送 POST 请求出现异常！" + e);
    		  e.printStackTrace();
    	  }
    	  // 使用finally块来关闭输出流、输入流
    	  finally {
    		  try {
    			  if (out != null) {
    				  out.close();
    			  }
    			  if (in != null) {
    				  in.close();
    			  }
    		  } catch (IOException ex) {
    			  ex.printStackTrace();
    		  }
    	  }
    	  System.out.println(result);
    	  return result;
      }
      
      public static Map<String, Object> beanToMap(Object obj) { 
    	    Map<String, Object> params = new HashMap<String, Object>(0); 
    	    try { 
    	      PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean(); 
    	      PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj); 
    	      for (int i = 0; i < descriptors.length; i++) { 
    	        String name = descriptors[i].getName(); 
    	        if (!StringUtils.equals(name, "class")) { 
    	        	params.put(name, propertyUtilsBean.getNestedProperty(obj, name)); 
    	        } 
    	      } 
    	    } catch (Exception e) { 
    	      e.printStackTrace(); 
    	    } 
    	    return params; 
    	}
      
      
      public static Map<String, Object> getUrlParams(String param) {  
          Map<String, Object> map = new HashMap<String, Object>(0);  
          if (StringUtils.isBlank(param)) {  
              return map;  
          }  
          String[] params = param.split("&");  
          for (int i = 0; i < params.length; i++) {  
              String[] p = params[i].split("=");  
              if (p.length == 2) {  
                  map.put(p[0], p[1]);  
              }  
          }  
          return map;  
      }  
    
      /** 
       * 将map转换成url 
       * @param map 
       * @return 
       */  
      public static String getUrlParamsByJavaBean(Object obj) {  
    	  Map<String, Object> map = beanToMap(obj);
          if (map == null) {  
              return "";  
          }  
          StringBuffer sb = new StringBuffer();  
          for (Map.Entry<String, Object> entry : map.entrySet()) {
        	  if(entry.getValue()!=null && entry.getValue() != ""){
        		  sb.append(entry.getKey() + "=" + entry.getValue());  
        		  sb.append("&");  
        	  }
          }  
          String s = sb.toString();  
          if (s.endsWith("&")) {  
              s = StringUtils.substringBeforeLast(s, "&");  
          }  
          return s;  
      }  
      
      public static void main(String[] args){
    	  String url = "http://cx.cheryfs.cn:9003/report/reportConfig/getSqlList";
    	  String str = sendGet(url, "p[1].fv=&p[1].fn=CUST_ID&p[1].lo=eq&p[1].tp=string&p[1].dt=VARCHAR2&p[2].fv=&p[2].fn=CUST_NAME&p[2].lo=eq&p[2].tp=string&p[2].dt=VARCHAR2&p[3].fv=&p[3].fn=ID_NO&p[3].lo=eq&p[3].tp=string&p[3].dt=VARCHAR2&p[4].fv=0&p[4].fn=CAR_PRODUCT&p[4].lo=eq&p[4].tp=dic&p[4].dt=VARCHAR2&userId=U005E&taskId=227.&_search=false&nd=1501149176&rows=8000&page=1&sidx=&sord=asc&confId=201411110738", "", "");
    	  System.out.println(str);
      }
      
}
